package com.ai.chat.service.impl;

import com.ai.chat.entity.Conversation;
import com.ai.chat.entity.Message;
import com.ai.chat.mapper.MessageMapper;
import com.ai.chat.service.AIService;
import com.ai.chat.service.ConversationService;
import com.ai.chat.service.MessageService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private ConversationService conversationService;

    @Autowired
    private AIService aiService;

    @Override
    @Transactional
    public Map<String, Message> sendMessage(Long userId, Long conversationId, String content) {
        Assert.notNull(userId, "用户ID不能为空");
        Assert.notNull(conversationId, "对话ID不能为空");
        Assert.hasText(content, "消息内容不能为空");

        // 验证对话是否存在且属于当前用户
        Conversation conversation = conversationService.getConversationById(conversationId);
        Assert.isTrue(conversation.getUserId().equals(userId), "无权操作此对话");

        // 保存用户消息
        Message userMessage = new Message();
        userMessage.setConversationId(conversationId);
        userMessage.setUserId(userId);
        userMessage.setContent(content);
        userMessage.setRole("user");
        userMessage.setCreateTime(LocalDateTime.now());
        userMessage.setIsDeleted(0);
        messageMapper.insert(userMessage);

        // 更新对话更新时间
        conversation.setUpdateTime(LocalDateTime.now());
        conversationService.updateConversationTitle(userId, conversationId, conversation.getTitle());

        // 调用AI服务生成回复
        String aiResponse = aiService.generateResponse(content);

        // 保存AI回复
        Message aiMessage = new Message();
        aiMessage.setConversationId(conversationId);
        aiMessage.setUserId(userId);
        aiMessage.setContent(aiResponse);
        aiMessage.setRole("assistant");
        aiMessage.setCreateTime(LocalDateTime.now());
        aiMessage.setIsDeleted(0);
        messageMapper.insert(aiMessage);

        // 返回用户消息和AI回复
        Map<String, Message> result = new HashMap<>();
        result.put("userMessage", userMessage);
        result.put("aiMessage", aiMessage);

        return result;
    }

    @Override
    public List<Message> getMessagesByConversationId(Long conversationId, Long userId) {
        Assert.notNull(conversationId, "对话ID不能为空");
        Assert.notNull(userId, "用户ID不能为空");

        // 验证对话是否存在且属于当前用户
        Conversation conversation = conversationService.getConversationById(conversationId);
        Assert.isTrue(conversation.getUserId().equals(userId), "无权查看此对话消息");

        return messageMapper.selectByConversationId(conversationId);
    }

    @Override
    public boolean deleteMessage(Long messageId, Long userId) {
        Assert.notNull(messageId, "消息ID不能为空");
        Assert.notNull(userId, "用户ID不能为空");

        // 验证消息是否存在且属于当前用户
        Message message = messageMapper.selectById(messageId);
        Assert.notNull(message, "消息不存在");

        // 验证消息所属对话是否属于当前用户
        Conversation conversation = conversationService.getConversationById(message.getConversationId());
        Assert.isTrue(conversation.getUserId().equals(userId), "无权删除此消息");

        // 软删除
        UpdateWrapper<Message> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", messageId)
                     .set("is_deleted", 1);

        return messageMapper.update(null, updateWrapper) > 0;
    }
}